import axios from "axios";
import { initialSDKModule } from "./Engine";
export const SCRIPT_TYPE_REGEX = /<script microprefetch src=(((?!(\>|bmap|mapbox)).)*)><\/script>?/g;
let isPreFetching = false;
let isPreFetched = false;
function getTPL() {
  return new Promise((resolve, reject) => {
    axios
      .get("/blackhole/index.html")
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

const loadScript = (url, cb) => {
  const script = document.createElement("script");
  script.type = "text/javascript";
  script.onload = () => {
    cb && cb();
  };
  script.src = url;
  document.querySelector("head")?.appendChild(script);
};

function loadScriptP(url) {
  return new Promise((resolve) => {
    loadScript(url, resolve);
  });
}

export async function doPrefetchBlackHole(options) {
  const { callback } = options ?? {};
  if (isPreFetching || isPreFetched) {
    return;
  }
  isPreFetching = true;
  try {
    const tpl = await getTPL();
    const promises = [];
    tpl.replace(SCRIPT_TYPE_REGEX, (match, configString, s2) => {
      const normalieUrl = "/blackhole/" + configString.replace(/(\"|\')/g, "");
      promises.push(loadScriptP(normalieUrl));
      return "";
    });
    await Promise.all(promises);
    callback?.();
    initialSDKModule();
    isPreFetched = true;
  } catch (e) {
    isPreFetching = false;
    isPreFetched = false;
  }
}

export function prefetchBlackHole() {
  // 本地开发用，在 localStorage 里 手动设置 __dangerousDisableBlackhole 会禁止黑洞引擎加载，以提高开发体验
  const __dangerousDisableBlackhole = localStorage.getItem(
    "__dangerousDisableBlackhole"
  );
  if (__dangerousDisableBlackhole) return;

  doPrefetchBlackHole({
    callback: () => {
      // 兼容黑洞那边的写法，并覆盖黑洞那边的设置
      window.serverUrl = window.location.origin + "/newblackholeapi";
      window.baseDataUrl = window.location.origin + "/newblackholeapi";
      window.imageBaseUrl = window.location.origin + "/newblackholeapi/files";
    },
  });
}
